<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :close-func="closeFunc"
    @ok="handleSubmit"
    destroy-on-close
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './data';

  import { addDeptApi, updateDeptApi } from '@/api/system/dept';
  import type { SystemDeptItem } from '@/api/system/model/deptModel';

  const rowId = ref('');
  const ancestors = ref('');
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    const { id } = data;
    ancestors.value = data.ancestors;

    rowId.value = id;
    if (id) {
      setFieldsValue({ ...data });
    }
    setFieldsValue({ parentId: ancestors.value });
  });

  const getTitle = computed(() => (!unref(rowId) ? '添加部门' : '修改部门'));

  const closeFunc = async () => {
    ancestors.value = '';
    rowId.value = '';
    await resetFields();
    return true;
  };

  async function handleSubmit() {
    try {
      const values: SystemDeptItem = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      unref(rowId)
        ? await updateDeptApi({
            ...values,
            id: rowId.value,
            ancestors: ancestors.value,
            parentId: values.parentId
              ? values.parentId.split(',')[values.parentId.split(',').length - 1]
              : null,
          })
        : await addDeptApi({
            ...values,
            ancestors: values.parentId,
            parentId: values.parentId
              ? values.parentId.split(',')[values.parentId.split(',').length - 1]
              : null,
          });
      closeModal();
      closeFunc();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
